package com.braveman.im.ui.activity.message;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.braveman.im.R;
import com.braveman.im.bean.CreateGroupInfoBean;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.weiget.ClearEditText;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.UIUtils;
import com.vondear.rxtools.RxBarTool;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class CreateGroupActivity extends BaseActivity {
    private ClearEditText mCetActivityCreateGroupProposer;
    private ClearEditText mCetActivityCreateGroupName;
    private ClearEditText mCetActivityCreateGroupCompanyIntroduce;
    private ClearEditText mCetActivityCreateGroupCompanyOrganizingCode;
    private ImageView mIvActivityCreateGroupCompanyPhoto;
    private TextView mBtnActivityCreateGroupUpdate;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/GROUP_INFO.jpg";
    private static final String TAKE_PHOTO_ICON_PATH = "ht/jkm/photo/GROUP_ICON.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CODE_TAKE_ICON_PHOTO = 4;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int REQUEST_CAMERA_ICON_CODE = 3;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private String picturePath;
    private String picUrl;
    private String groupCategoryId;
    private ImageView mIvActivityCreateGroupCompanyIcon;
    private String picturePath1;
    private String picUrl1;


    @Override
    protected void initIntentData(Intent callIntent) {
        groupCategoryId = callIntent.getStringExtra("groupCategoryId");
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("编辑企业资料").setLeftBtnIcon(R.mipmap.back_black).setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.finishActivity(CreateGroupActivity.this);
            }
        });
    }

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_create_group;
    }

    @Override
    protected void initChildView() {
        mCetActivityCreateGroupProposer = (ClearEditText) findViewById(R.id.cet_activity_create_group_proposer);
        mCetActivityCreateGroupName = (ClearEditText) findViewById(R.id.cet_activity_create_group_name);
        mCetActivityCreateGroupCompanyIntroduce = (ClearEditText) findViewById(R.id.cet_activity_create_group_company_introduce);
        mCetActivityCreateGroupCompanyOrganizingCode = (ClearEditText) findViewById(R.id.cet_activity_create_group_company_organizing_code);
        mIvActivityCreateGroupCompanyPhoto = (ImageView) findViewById(R.id.iv_activity_create_group_company_photo);
        mBtnActivityCreateGroupUpdate = (TextView) findViewById(R.id.btn_activity_create_group_update);
        mIvActivityCreateGroupCompanyIcon = (ImageView) findViewById(R.id.iv_activity_create_group_company_icon);
    }

    @Override
    protected void initChildData() {
        mIvActivityCreateGroupCompanyPhoto.setOnClickListener(this);
        mBtnActivityCreateGroupUpdate.setOnClickListener(this);
        mIvActivityCreateGroupCompanyIcon.setOnClickListener(this);
    }

    @Override
    protected void setChildViewListener() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_activity_create_group_company_photo:
                try {
                    InputMethodManager im = (InputMethodManager) CreateGroupActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(CreateGroupActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(0);
                    } else {
                        ActivityCompat.requestPermissions(CreateGroupActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(CreateGroupActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.iv_activity_create_group_company_icon:
                try {
                    InputMethodManager im = (InputMethodManager) CreateGroupActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(CreateGroupActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(1);
                    } else {
                        ActivityCompat.requestPermissions(CreateGroupActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(CreateGroupActivity.this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
            case R.id.btn_activity_create_group_update:
                String groupProposer = mCetActivityCreateGroupProposer.getText().toString().trim();
                String groupName = mCetActivityCreateGroupName.getText().toString().trim();
                String companyIntroduce = mCetActivityCreateGroupCompanyIntroduce.getText().toString().trim();
                String organizingCode = mCetActivityCreateGroupCompanyOrganizingCode.getText().toString().trim();
                CreateGroupInfoBean createGroupInfoBean = new CreateGroupInfoBean();
                createGroupInfoBean.legalPerson = groupProposer;//申请人、法人
                createGroupInfoBean.applicationPhoto = picUrl;//申请照片
                createGroupInfoBean.corpName = groupName;//企业名称
                createGroupInfoBean.groupType = "company";//群类型
                createGroupInfoBean.organizationCode = organizingCode;//组织机构代码
                createGroupInfoBean.corpDescription = companyIntroduce;//企业介绍
                createGroupInfoBean.icon = picUrl1;//企业logo
//                createGroupInfoBean.applicationPhoto = picUrl;//申请照片

                ApiManager.getApi().UpdateGroupInfo(createGroupInfoBean).enqueue(new NetCallBack<CreateGroupInfoBean>() {
                    @Override
                    protected void onSuccess(Call<CreateGroupInfoBean> call, Response<CreateGroupInfoBean> response) {
                        CreateGroupInfoBean createGroupInfoBean1 = response.body();
                        UIUtils.showToast("企业群已提交，请等待审核");
                        ActivityUtils.finishActivity(CreateGroupActivity.this);

                    }
                });
                break;
        }
    }

    private void takePicture(final int count) {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), count == 0 ? TAKE_PHOTO_PATH : TAKE_PHOTO_ICON_PATH);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(CreateGroupActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                CreateGroupActivity.this.startActivityForResult(intent, count == 0 ? REQUEST_CODE_TAKE_PHOTO : REQUEST_CODE_TAKE_ICON_PHOTO);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, count == 0 ? REQUEST_CAMERA_CODE : REQUEST_CAMERA_ICON_CODE);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case 200: //图片
                int type = (int) msg.obj;
                String path = "";
                switch (type) {
                    case 0:
                        path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                        Glide.with(CreateGroupActivity.this)//
                                .load(path)//
                                .into(mIvActivityCreateGroupCompanyPhoto);
                        toUpdata(path, 0);
                        break;
                    case 1:
                        path = picturePath;
                        Glide.with(CreateGroupActivity.this)//
                                .load(path)//
                                .into(mIvActivityCreateGroupCompanyPhoto);
                        toUpdata(path, 0);
                        break;
                    case 2:
                        path = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_ICON_PATH;
                        Glide.with(CreateGroupActivity.this)//
                                .load(path)//
                                .into(mIvActivityCreateGroupCompanyIcon);
                        toUpdata(path, 1);
                        break;
                    case 3:
                        path = picturePath1;
                        Glide.with(CreateGroupActivity.this)//
                                .load(path)
                                .into(mIvActivityCreateGroupCompanyIcon);
                        toUpdata(path, 1);
                        break;

                }
        }
    }

    private void toUpdata(String path, final int count) {
        File file = new File(path);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {


            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                PicUpdateBean picUpdateBean = response.body().get(0);
                if (count == 0) {
                    picUrl = picUpdateBean.url;
                } else {
                    picUrl1 = picUpdateBean.url;
                }
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CODE_TAKE_ICON_PHOTO:
                    String filePath1 = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_ICON_PATH;
                    new CompressPhotoThread(mHandler, filePath1, 2).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    break;
                case REQUEST_CAMERA_ICON_CODE:
                    Uri selectedImage1 = data.getData();
                    String[] filePathColumn1 = {MediaStore.Images.Media.DATA};
                    Cursor cursor1 = this.getContentResolver().query(selectedImage1,
                            filePathColumn1, null, null, null);
                    cursor1.moveToFirst();
                    int columnIndex1 = cursor1.getColumnIndex(filePathColumn1[0]);
                    picturePath1 = cursor1.getString(columnIndex1);
                    cursor1.close();
                    new CompressPhotoThread(mHandler, picturePath1, 3).start();
                    break;

            }
        }

    }

}
